﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Mobile.Mvc;

namespace MVCDemoClient
{
    public class SearchController : Controller<Products>
    {
        Products products;

        [PublishEvent("OnProductsUpdated")]
        public event EventHandler ProductsUpdated;

        public SearchController(IView<Products> view)
            : base(view)
        {                       
            // Create an intance of the Products
            products = new Products();
            // Populate the list
            products.PopulateList();            
            // Assign the Model
            this.view.ViewData.Model = products;
            // Notify the view of the changes
            this.NotifyView();
        }

        // Search event from the view
        private void OnSearch(object sender, DataEventArgs<string> e)
        {
            this.view.ViewData.Model.FilterData(e.Value);
            // Notify the view
            this.NotifyView();
        }

        // Selected event from the view
        private void OnSelected(object sender, DataEventArgs<NorthwindDataSet.ProductsRow> e)
        {
            this.ShowDetailView(e.Value);            
        }

        private void NotifyView()
        {
            // Raise the event for view
            if (this.ProductsUpdated != null)
            {
                this.ProductsUpdated(this, EventArgs.Empty);
            }
        }

        private void ShowDetailView(NorthwindDataSet.ProductsRow product)
        {
            DetailController controller = new DetailController(new DetailForm());
            NavigationService.Navigate(controller, product);
        }

    }
}
